/**
 * author      : dormi330
 * date        : 2017/9/8
 * project     : open_sdk_java
 * description : 微店Sdk 测试
 */

package sdk.demo;

import com.weidian.open.sdk.AbstractWeidianClient;
import com.weidian.open.sdk.DefaultWeidianClient;
import com.weidian.open.sdk.entity.Cate;
import com.weidian.open.sdk.entity.Item;
import com.weidian.open.sdk.entity.Sku;
import com.weidian.open.sdk.exception.OpenException;
import com.weidian.open.sdk.request.AbstractRequest;
import com.weidian.open.sdk.request.product.*;
import com.weidian.open.sdk.response.AbstractResponse;
import com.weidian.open.sdk.response.Status;
import com.weidian.open.sdk.response.oauth.OAuthResponse;
import com.weidian.open.sdk.response.product.VdianItemListGetResponse;
import com.weidian.open.sdk.response.product.VdianShopCateGetResponse;
import com.weidian.open.sdk.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class VdianSdkDemo {
    public static final Logger log = LoggerFactory.getLogger(VdianSdkDemo.class);


    //
    private static final String VDIAN_APPKEY = "686216";
    private static final String VDIAN_SECRET = "6cf7943d421315dd4d4ec699f2210a18";

    private static final AbstractWeidianClient vdianClient = new DefaultWeidianClient();

    public static void main(String[] args) {
//        getVdianAccesstoken();


//        pushImageGetUrl();
//        addVdianItem();

        // 分类相关
        getShopCate();
//        deleteAllShopCate();
//        addShopCate("女装");


//        getItemList();
//        deleteAllItems();
//        itemOnSale();
//        itemOffSale();
    }


    private static String VDIAN_ACCESSTOKEN = "d421013f86166a73ef3a1629bbde59120007721503";
    private static final String VDIAN_URL_GETACCESSTOKEN = "https://oauth.open.weidian.com/token?grant_type=client_credential&appkey=%s&secret=%s";

    // 获取 VDIAN_ACCESSTOKEN
    private static String getVdianAccesstoken() {

        // init
        VDIAN_ACCESSTOKEN = null;
        String url = String.format(VDIAN_URL_GETACCESSTOKEN, VDIAN_APPKEY, VDIAN_SECRET);

        // 发起一个 get 请求
        try {
            String respStr = vdianClient.executeGetForString(url);
            OAuthResponse resp = JsonUtils.toObject(respStr, OAuthResponse.class);
            VDIAN_ACCESSTOKEN = resp.getAccessToken();
            log.debug("getVdianAccesstoken, result = " + VDIAN_ACCESSTOKEN);
            return VDIAN_ACCESSTOKEN;
        } catch (OpenException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getBytesFromImgUrl(String imgUrl) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            URL url = new URL(imgUrl);

            is = url.openStream();
            byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
            int n;
            while ((n = is.read(byteChunk)) > 0) {
                baos.write(byteChunk, 0, n);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            System.err.printf("Failed while reading bytes from %s: %s", imgUrl, e.getMessage());
            e.printStackTrace();
            // Perform any other exception handling that's appropriate.
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // if fail return null;
        return null;

    }


//    private static final String VDIAN_SAMPLE_IMG = "https://si.geilicdn.com/bj-open-1250968661-1504853358955-682380474_540_258.jpg?w=540&h=258";
    private static final String VDIAN_SAMPLE_IMG="https://www.baidu.com/img/bd_logo1.png";

    // 从 一个url 获取图片,然后推送到 vdian
    // https://stackoverflow.com/questions/2295221/java-net-url-read-stream-to-byte
    private static String pushImageGetUrl() {
        String imgUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
        byte[] imgContent = getBytesFromImgUrl(imgUrl);
        if (imgContent == null) {
            log.error("cannot get data from url=" + imgUrl);
            return null;
        }

        log.trace("开始推送图片");
        MediaUploadRequest request = new MediaUploadRequest(VDIAN_ACCESSTOKEN, imgContent);
        try {
            AbstractResponse response = vdianClient.multipart(request);
            // https://si.geilicdn.com/bj-open-1250968661-1504853358955-682380474_540_258.jpg?w=540&h=258
            log.debug("response:{}\n", response.toString());
        } catch (OpenException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void testCommon(AbstractRequest request) {
        try {
            // AbstractResponse response = client.executeGet(request);
            AbstractResponse response = vdianClient.executePost(request);
//            log.debug("response:{}\n", response.toString());
        } catch (OpenException e) {
            e.printStackTrace();
        }
    }

    // 添加分类 & 获取分类
    private static void addShopCate(String cateName) {
        if (cateName == null) cateName = "女装";
        log.debug("addShopCate + cateName=" + cateName);
        Cate cate = new Cate();
        cate.setCateName(cateName);
        cate.setSortNum(1);
        // 添加分类
        testCommon(new VdianShopCateAddRequest(VDIAN_ACCESSTOKEN, new Cate[]{cate}));
    }

    // 获取分类
    private static void getShopCate() {
        log.debug("getShopCate");
        testCommon(new VdianShopCateGetRequest(VDIAN_ACCESSTOKEN));
    }


    private static void deleteAllShopCate() {
        log.debug("deleteAllShopCate");
        // 获取分类
        try {
            AbstractRequest<VdianShopCateGetResponse> request = new VdianShopCateGetRequest(VDIAN_ACCESSTOKEN);
            VdianShopCateGetResponse response = vdianClient.executePost(request);
//            log.debug("response:{}\n", response.toString());

            Status status = response.getStatus();
            if (status == null) {
                log.debug("null status");
                return;
            }
            if (!status.isOk()) {
                log.debug("status not ok,stauts_code=" + status.getStatusCode());
                return;
            }

            Cate[] cates = response.getResult();

            for (Cate aCate : cates) {
                String cateId = aCate.getCateId();
                AbstractRequest deleteCateRequest = new VdianShopCateDeleteRequest(VDIAN_ACCESSTOKEN, cateId);
                log.debug("delete shop cate, cateId=" + cateId + ",name=" + aCate.getCateName());
                vdianClient.executePost(deleteCateRequest);
            }

        } catch (OpenException e) {
            e.printStackTrace();
        }
    }

    private static final String CATE_ID_A="109361718";
    // 添加商品型号
    private static void addVdianItem() {
        Item item = new Item();
        item.setItemName("多规女装");
        item.setImgs(new String[]{VDIAN_SAMPLE_IMG});
        item.setPrice("0.01");
        item.setStock(100);

        Sku sku = new Sku();
        sku.setTitle("测试型号1");
        sku.setPrice("0.01");
        sku.setSkuMerchantCode("gmcTestSkuX");
        sku.setStock(100);
        item.setSkus(new Sku[]{sku});

        testCommon(new VdianItemAddRequest(VDIAN_ACCESSTOKEN, item));
    }

    // 修改库存
    private static void changeStock() {

    }

    // 获取店铺所有商品
    private static void getItemList() {
        testCommon(new VdianItemListGetRequest(VDIAN_ACCESSTOKEN));
    }

    // 删除商品
    private static void deleteAllItems() {

        try {
            // AbstractResponse response = client.executeGet(request);
            VdianItemListGetResponse response = vdianClient.executePost(new VdianItemListGetRequest(VDIAN_ACCESSTOKEN));
            log.debug("response:{}\n", response.toString());
            Item[] items = response.getResult().getItems();
            for (Item item : items) {
                String id = item.getItemId();
                System.out.println("delete item, id=" + id);
                testCommon(new VdianItemDeleteRequest(VDIAN_ACCESSTOKEN, id));
            }
        } catch (OpenException e) {
            e.printStackTrace();
        }

    }


    // 上架商品
    // 测试发现 此方法幂等
    private static void itemOnSale() {
        testCommon(new WeidianItemOnSaleRequest(VDIAN_ACCESSTOKEN, "2162904983", 1));
    }


    // 上架商品
    // 测试发现 此方法幂等
    private static void itemOffSale() {
        testCommon(new WeidianItemOnSaleRequest(VDIAN_ACCESSTOKEN, "2162904983", 2));
    }
}
